package repository

import (
	"gorm.io/gorm"
	"shop-sys/model"
)

type ISysUserRoleRepository interface {
	CreateUserAndUserRole(*gorm.DB, uint, []uint) error
	FindListRoleIdByUserId(*gorm.DB, uint) ([]uint, error)
	DeleteByUserId(*gorm.DB, uint) error
	DeleteBatch(*gorm.DB, []uint) error
}

type sysUserRoleRepository struct {
}

func NewSysUserRoleRepository() ISysUserRoleRepository {
	return &sysUserRoleRepository{}
}

func (ur *sysUserRoleRepository) CreateUserAndUserRole(db *gorm.DB, userId uint, roleIdList []uint) error {
	var userRoles []*model.SysUserRole
	for _, roleId := range roleIdList {
		u := model.SysUserRole{
			UserId: userId,
			RoleId: roleId,
		}
		userRoles = append(userRoles, &u)
	}

	return db.Create(userRoles).Error
}

type partRoleIds struct {
	RoleId uint
}

func (ur *sysUserRoleRepository) FindListRoleIdByUserId(db *gorm.DB, userId uint) (roleIdList []uint, err error) {
	var partList []*partRoleIds
	err = db.Model(&model.SysUserRole{}).Select("role_id").Where("user_id = ?", userId).Find(&partList).Error
	if err != nil {
		return nil, err
	}

	for _, item := range partList {
		roleIdList = append(roleIdList, item.RoleId)
	}

	return roleIdList, nil
}

/**
 * 根据用户id删除用户与角色关系
 * @param userId
 */
func (ur *sysUserRoleRepository) DeleteByUserId(db *gorm.DB, id uint) error {
	return db.Delete(&model.SysUserRole{}, id).Error
}

/**
 * 根据角色ID数组，批量删除
 */
func (ur *sysUserRoleRepository) DeleteBatch(db *gorm.DB, roleIds []uint) error {
	return db.Where("role_id IN ?", roleIds).Delete(&model.SysUserRole{}).Error
}
